//
//  MineOrderViewController.m
//  PYWGetColor
//
//  Created by 杜文杰 on 2018/6/7.
//  Copyright © 2018年 dwj. All rights reserved.
//

#import "MineOrderViewController.h"
#import "TopMenuView.h"
#import "MineOrderTableViewCell.h"
#import "MineOrderTwoTableViewCell.h"
#import "MakeSureMoneyView.h"
#import "MineOrderQiangdanTableViewCell.h"
#import "AppraiseViewController.h"
#import "MineOrderModel.h"
#import "AppraiseViewController.h"
#import "WJChatViewController.h"
#import "DetailMakeSureViewController.h"
#import "MineOrderModel.h"

static NSString *stateStaStr;
@interface MineOrderViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *mainTableView; // 主框架
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UIView *footerView;
@property (nonatomic, strong) MineOrderModel *mineOrderModel;
@property (nonatomic, strong) NSMutableArray *datamuArray;
@property (nonatomic, strong) NSString *orderid;// 订单号
@property (nonatomic, strong) NSString *order_sn;// 微信支付用到的编号
@property (nonatomic, strong) NSString *shouldPayMoney;// 需要支付金额
@property (nonatomic, strong) MakeSureMoneyView *makeSureMoneyView;
@property (nonatomic, strong) TopMenuView *topView;
@end

@implementation MineOrderViewController
/**
 我的需求接口
 */
- (void)myOrderDemand {
    [self.datamuArray removeAllObjects];
    self.mineOrderModel = nil;
    [self.mainTableView reloadData];
    [[AFAppDotNetAPIClient sharedClient] POST:@"interface.php?m=mydemand" parameters:@{@"uid":[UserModel sharedInstanced].userId,@"token":[UserModel sharedInstanced].token} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"error_code"] isEqualToString:@"0"]) {
            self.mineOrderModel = [MineOrderModel yy_modelWithDictionary:responseObject];
            [self.datamuArray addObjectsFromArray:self.mineOrderModel.data];
        }
        [self.mainTableView reloadData];
        ShowMessage(responseObject[@"message"]);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError:error];
    }];
}
/**
 我的服务接口
 */
- (void)mineServers {
    [self.datamuArray removeAllObjects];
    [[AFAppDotNetAPIClient sharedClient] POST:@"interface.php?m=ordertome" parameters:@{@"uid":[UserModel sharedInstanced].userId,@"token":[UserModel sharedInstanced].token} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"error_code"] isEqualToString:@"0"]) {
            self.mineOrderModel = [MineOrderModel yy_modelWithDictionary:responseObject];
            [self.datamuArray addObjectsFromArray:self.mineOrderModel.data];
        }
        [self.mainTableView reloadData];
        ShowMessage(responseObject[@"message"]);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError:error];
    }];
}
// 余额支付 （如果余额不足 直接调用微信支付）
//参数名    必选    类型    说明
//uid    是    int    uid
//token    是    string    token
//orderid    是    string    订单id
//shouldpaymoney    是    string    订单应该支付的价格
- (void)systemYuePay{
    NSDictionary *parameter = @{@"uid":[UserModel sharedInstanced].userId,@"token":[UserModel sharedInstanced].token,@"orderid":self.orderid,@"shouldpaymoney":self.shouldPayMoney};
    [[AFAppDotNetAPIClient sharedClient]POST:@"interface.php?m=finishorder" parameters:parameter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@",responseObject);
        if ([responseObject[@"data"][@"status"] isEqualToString:@"1"]) { // 余额扣款
            [self.makeSureMoneyView hidden];
            dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0/*延迟执行时间*/ * NSEC_PER_SEC));
            dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                ShowMessage(@"余额扣款成功");
            });
            [self myOrderDemand];
        }else{ // 余额不足 直接微信支付
            [self wxPayForRechare];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError:error];
    }];
}
// 微信支付成功回调 修改订单状态
- (void)wxPayBlackInfoMation{
    NSDictionary *parameter = @{@"uid":[UserModel sharedInstanced].userId,@"token":[UserModel sharedInstanced].token,@"orderid":self.orderid,@"shouldpaymoney":self.shouldPayMoney};
    [[AFAppDotNetAPIClient sharedClient]POST:@"interface.php?m=wx_finish" parameters:parameter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@",responseObject);
        [self myOrderDemand];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError:error];
    }];
}
// 微信支付
- (void)wxPayForRechare{
    NSDictionary *parameter = @{@"total":self.shouldPayMoney,@"order_sn":self.order_sn};
    [[AFAppDotNetAPIClient sharedClient]POST:@"interface.php?m=wxpay" parameters:parameter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@",responseObject);
        [self weiXinpay:responseObject[@"data"]];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError:error];
    }];
}
/**
 微信支付
 */
- (void)weiXinpay:(NSDictionary *)dic{
    PayReq *request = [[PayReq alloc]init];
    request.partnerId = dic[@"partnerid"];
    request.prepayId= dic[@"prepayid"];
    request.package = dic[@"package"];
    request.nonceStr= dic[@"noncestr"];
    request.timeStamp= [dic[@"timestamp"] intValue];
    request.sign= dic[@"sign"];
    [WXApi sendReq:request];
}
/**
 取消订单
 参数名  同上
 */
- (void)orderCancel {
    [self.datamuArray removeAllObjects];
    [[AFAppDotNetAPIClient sharedClient] POST:@"interface.php?m=orderCancel" parameters:@{@"uid":[UserModel sharedInstanced].userId,@"token":[UserModel sharedInstanced].token,@"orderid":self.orderid} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"error_code"] isEqualToString:@"0"]) {
            ShowMessage(@"操作成功");
            [self myOrderDemand];
        }else{
            ShowMessage(responseObject[@"message"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError:error];
    }];
}

/**
 点击完成服务
 参数名 同上
 */
- (void)overServer {
    [self.datamuArray removeAllObjects];
    [[AFAppDotNetAPIClient sharedClient] POST:@"interface.php?m=completeservice" parameters:@{@"uid":[UserModel sharedInstanced].userId,@"token":[UserModel sharedInstanced].token,@"orderid":self.orderid} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"error_code"] isEqualToString:@"0"]) {
            [self mineServers];
        }else{
            ShowMessage(responseObject[@"message"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError:error];
    }];
}
/**
 确认接单
 */
- (void)MakeSureOrder {
    [self.datamuArray removeAllObjects];
    [[AFAppDotNetAPIClient sharedClient] POST:@"interface.php?m=confirmorder" parameters:@{@"uid":[UserModel sharedInstanced].userId,@"token":[UserModel sharedInstanced].token,@"orderid":self.orderid,@"state":@"1"} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"error_code"] isEqualToString:@"0"]) {
            [self mineServers];
        }else{
            ShowMessage(responseObject[@"message"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError:error];
    }];
}
/**
 拒绝接单
 */
- (void)refuseOrder {
    [self.datamuArray removeAllObjects];
    [[AFAppDotNetAPIClient sharedClient] POST:@"interface.php?m=confirmorder" parameters:@{@"uid":[UserModel sharedInstanced].userId,@"token":[UserModel sharedInstanced].token,@"orderid":self.orderid,@"state":@"0"} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"error_code"] isEqualToString:@"0"]) {
            ShowMessage(@"拒单成功");
            [self mineServers];
        }else{
            ShowMessage(responseObject[@"message"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError:error];
    }];
}
//微信支付成功后通知跳转界面
- (void) alipayBackOverNotification
{
    [self.makeSureMoneyView hidden];
    dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0/*延迟执行时间*/ * NSEC_PER_SEC));
    dispatch_after(delayTime, dispatch_get_main_queue(), ^{
        [self myOrderDemand];
    });
    
//    [self wxPayBlackInfoMation]; // 支付成功 修改订单状态 （改为后台处理）
}

- (void)viewDidLoad {
    [super viewDidLoad];
    TopMenuView *topView = [[TopMenuView alloc]init];
    self.topView = topView;
    CGRect viewRect = CGRectMake(0, 0, SCREEN_WIDTH, 40);
    topView.frame = viewRect;
    [self.view addSubview:topView];
    
    self.typeStr = @"QD";
    [self.mainTableView reloadData];
    topView.btnTagBlock = ^(NSString *btnstr) {
        if ([btnstr isEqualToString:@"1"]) {
            NSLog(@"我要抢单");
            self.typeStr = @"QD";
            stateStaStr = self.typeStr;
            [self.mainTableView reloadData];
        }
        if ([btnstr isEqualToString:@"2"]) {
            NSLog(@"我要需求");
            self.typeStr = @"XQ";
            stateStaStr = self.typeStr;
            [self myOrderDemand];
        }
        if ([btnstr isEqualToString:@"3"]) {
            NSLog(@"我的服务");
            self.typeStr = @"FW";
            stateStaStr = self.typeStr;
            [self mineServers];
        }
    };
    
    [self.view addSubview:self.mainTableView];
    __weak typeof(self)weakself = self;
    [self.mainTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(topView.mas_bottom);
        make.left.right.bottom.equalTo(weakself.view);
    }];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
    self.title = @"我的订单";
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alipayBackOverNotification) name:@"wxpayBackOver" object:nil];
    
    if (self.stateStr == nil || self.stateStr == NULL || self.stateStr.length <= 0) {
        self.stateStr = stateStaStr;
        if ([stateStaStr isEqualToString:@"XQ"]) {
            self.stateStr = @"1";
        }
        if ([stateStaStr isEqualToString:@"FW"]) {
            self.stateStr = @"2";
        }
    }
    if ([self.stateStr isEqualToString:@"1"] ) {
        NSLog(@"我要需求");
        self.typeStr = @"XQ";
        self.topView.stateStr = @"1";
        [self myOrderDemand];
    }
    if ([self.stateStr isEqualToString:@"2"]) {
        NSLog(@"我的服务");
        self.typeStr = @"FW";
        self.topView.stateStr = @"2";
        [self mineServers];
    }
}
#pragma mark -UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.datamuArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MineOrderModelList *model = (MineOrderModelList *)self.datamuArray[indexPath.section];
    if ([self.typeStr isEqualToString:@"QD"]) {
        self.title = @"抢单";
        MineOrderQiangdanTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([MineOrderQiangdanTableViewCell class])];
        return cell;
    }
    if([self.typeStr isEqualToString:@"FW"]){
        self.title = @"我的服务";
        if ([model.order_status isEqualToString:@"1"]) {// 待确认 状态
            MineOrderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([MineOrderTableViewCell class])];
            cell.mineOrderModelList = model;
            cell.telephoneBtnBlock = ^{
                [self callPhone:model.worker_tel];
            };
            cell.doOrderBlock = ^{
                NSLog(@"确认接单");
                self.orderid = model.order_id;
                [self MakeSureOrder];
            };
            cell.unDoOrderBlock = ^{
                NSLog(@"拒绝接单");
                self.orderid = model.order_id;
                [self refuseOrder];
            };
            cell.talkAboutBtnBlock = ^{
                //环信聊天界面
                //聊天类型:EMConversationTypeChat
                WJChatViewController *chatController = [[WJChatViewController alloc] initWithConversationChatter:model.worker_tel conversationType:EMConversationTypeChat];
                [self.navigationController pushViewController:chatController animated:YES];
            };
            return cell;
        }else{
            MineOrderTwoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([MineOrderTwoTableViewCell class])];
            cell.myServerModelList = model;
            cell.talkAboutBtnBlock = ^{
                //环信ID:@"8001"
                //聊天类型:EMConversationTypeChat
                WJChatViewController *chatController = [[WJChatViewController alloc] initWithConversationChatter:model.worker_tel conversationType:EMConversationTypeChat];
                [self.navigationController pushViewController:chatController animated:YES];
            };
            cell.telephoneBtnBlock = ^{
                [self callPhone:model.worker_tel];
            };
            cell.btnActionBlock = ^(NSString *typeStr) {
                if ([model.order_status isEqualToString:@"2"]) {
                    NSLog(@"完成服务 %@",model.order_status);
                    self.orderid = model.order_id;
                    [self overServer];
                }
            };
            return cell;
        }
    }
    if ([self.typeStr isEqualToString:@"XQ"]) {
        self.title = @"我的需求";
        MineOrderTwoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([MineOrderTwoTableViewCell class])];
        cell.mineOrderModelList = model;
        cell.talkAboutBtnBlock = ^{
            //环信ID:@"8001"
            //聊天类型:EMConversationTypeChat
            WJChatViewController *chatController = [[WJChatViewController alloc] initWithConversationChatter:model.worker_tel conversationType:EMConversationTypeChat];
            [self.navigationController pushViewController:chatController animated:YES];
        };
        cell.telephoneBtnBlock = ^{
            [self callPhone:model.worker_tel];
        };
        cell.btnActionBlock = ^(NSString *typeStr) {
            if ([typeStr isEqualToString:@"1"]) {
                NSLog(@"取消订单 %@",model.order_status);
                self.orderid = model.order_id;
                [self orderCancel];
            }else if ([typeStr isEqualToString:@"3"]){
                NSLog(@"去支付 %@",model.order_status);
                self.orderid = model.order_id;
                self.order_sn = model.order_sn;
                self.shouldPayMoney = model.order_amount;
                // 确认支付
                MakeSureMoneyView *makeSureMoneyView = [[MakeSureMoneyView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
                makeSureMoneyView.moneyField.text = model.order_amount;
                makeSureMoneyView.makeSureBtnBlock = ^{
                    [self systemYuePay];
                };
                self.makeSureMoneyView = makeSureMoneyView;
                [makeSureMoneyView show];
            }else if ([typeStr isEqualToString:@"4"]){
                NSLog(@"去评价 %@",model.order_status);
                AppraiseViewController *VC = [[AppraiseViewController alloc]init];
                VC.mineOrderModelList = model;
                [self.navigationController pushViewController:VC animated:NO];
            }
            
        };
        return cell;
    }
    return nil;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DetailMakeSureViewController *VC = [[DetailMakeSureViewController alloc]init];
    VC.mineOrderModelList = (MineOrderModelList *)self.datamuArray[indexPath.section];
    VC.typeStrXq = @"1";
    [self.navigationController pushViewController:VC animated:NO];
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01f;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *bgView = [[UIView alloc]init];
    bgView.backgroundColor = getColor(dividerColor);
    
    return bgView;
}
#pragma mark - init
- (UITableView *)mainTableView
{
    if (!_mainTableView) {
        _mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - SafeAreaBottomHeight - SafeAreaTopHeight) style:UITableViewStyleGrouped];
        _mainTableView.backgroundColor = getColor(whiteColor);
        _mainTableView.tableHeaderView = self.headerView;
        _mainTableView.tableFooterView = self.footerView;
        _mainTableView.delegate = self;
        _mainTableView.dataSource = self;
        _mainTableView.showsVerticalScrollIndicator = NO;
        _mainTableView.showsHorizontalScrollIndicator = NO;
        _mainTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        // 动态行高
        _mainTableView.rowHeight = UITableViewAutomaticDimension;
        // 预估行高
        _mainTableView.estimatedRowHeight = 80;
        [_mainTableView registerClass:[MineOrderTableViewCell class] forCellReuseIdentifier:NSStringFromClass([MineOrderTableViewCell class])];
        [_mainTableView registerClass:[MineOrderTwoTableViewCell class] forCellReuseIdentifier:NSStringFromClass([MineOrderTwoTableViewCell class])];
        [_mainTableView registerClass:[MineOrderQiangdanTableViewCell class] forCellReuseIdentifier:NSStringFromClass([MineOrderQiangdanTableViewCell class])];
    }
    return _mainTableView;
}
- (UIView *)headerView
{
    if (!_headerView) {
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.01)];
        _headerView.backgroundColor = [UIColor grayColor];
    }
    return _headerView;
}
- (UIView *)footerView
{
    if (!_footerView) {
        _footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.01)];
    }
    return _footerView;
}
- (NSMutableArray *)datamuArray
{
    if (!_datamuArray) {
        _datamuArray = @[].mutableCopy;
    }
    return _datamuArray;
}
@end
